package com.study.ju.util.http.apachehttp;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * https://blog.csdn.net/klzyf100/article/details/78873222
 * @author 陈涛
 * @description: HttpClientTest
 * @Date 2018/5/17 15:23
 */
public class HttpsClientUtil {
    public static final String UTF8 = "UTF-8";
    public static final int STATUS_CODE = 200;
    public static final int TIME_OUT = 10000;
    private static Logger log = LoggerFactory.getLogger(HttpsClientUtil.class);

    /**
     * @param
     * @param timeOut
     * @return
     * @author 陈涛
     * @Date:2018/5/17 15:49
     */
    public static String sendHttpsGet(String url, Map<String, String> param, Integer timeOut) {
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("url为空");
        }
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        String responseValue = null;
        try {
            timeOut = timeOut != null ? timeOut : TIME_OUT;
            RequestConfig config = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
            // 2. 创建HttpGet对象
            StringBuilder sb = new StringBuilder();
            String requestUrl = null;
            sb.append(url);
            if (param != null && param.size() > 0) {
                sb.append("?");
                for (String key : param.keySet()) {
                    sb.append(key).append("=").append(URLEncoder.encode(param.get(key), "UTF-8")).append("&");
                }
                requestUrl = sb.toString().trim().substring(0, sb.toString().trim().length() - 1);
            } else {
                requestUrl = url;
            }
            HttpGet httpGet = new HttpGet(requestUrl);
            httpGet.setConfig(config);
            httpGet.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.6) Gecko/20100625Firefox/3.6.6 Greatwqs");
            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml,application/json");
            // 3. 执行GET请求
            response = httpClient.execute(httpGet);
            if (response != null) {
                responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (response.getStatusLine().getStatusCode() == HttpsClientUtil.STATUS_CODE) {
                    return responseValue;
                } else {
                    log.error("sendHttpGet error"+response.getStatusLine().getStatusCode());
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                if(response!=null){
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseValue;
    }

    public static String sendHttpPostForm(String url, Map<String, String> param, Integer timeOut) {
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("url为空");
        }
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        String responseValue = null;
        try {
            timeOut = timeOut != null ? timeOut : TIME_OUT;
            RequestConfig config = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
            // 2. 创建HttpGet对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(config);
            httpPost.setHeader("Accept-Charset", "utf-8");
            httpPost.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 3. 执行post请求
            response = httpClient.execute(httpPost);
            if (response != null) {
                responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (response.getStatusLine().getStatusCode() == HttpsClientUtil.STATUS_CODE) {
                    return responseValue;
                } else {
                    log.error("sendHttpGet error"+response.getStatusLine().getStatusCode());
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                if(response!=null){
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseValue;
    }

    public static String sendHttsPostJson(String url, String json, Integer timeOut) {
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("url为空");
        }
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        String responseValue = null;
        try {
            timeOut = timeOut != null ? timeOut : TIME_OUT;
            RequestConfig config = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
            // 2. 创建HttpGet对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(config);
            httpPost.setHeader("Accept-Charset", "utf-8");
            httpPost.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
            if (null != json) { // 解决中文乱码问题
                StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
                // entity.setContentEncoding(UTF8);
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            // 3. 执行post请求
            response = httpClient.execute(httpPost);
            if (response != null) {
                responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpsClientUtil.STATUS_CODE) {
                    return responseValue;
                } else {
                    log.error("sendHttpGet error"+response.getStatusLine().getStatusCode());
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                if(response!=null){
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseValue;
    }

    private static void enableSSL() {
        try {
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[]{manager}, null);
            socketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    private static TrustManager manager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    private static SSLConnectionSocketFactory socketFactory;

    /**
     * 获取
     * @return
     */
    public static CloseableHttpClient getHttpClient() {
        //采用绕过验证的方式处理https请求
        enableSSL();
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
        // // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //创建自定义的httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
        return httpClient;
    }

    public static void main(String[] args) {
        String s = HttpsClientUtil.sendHttpsGet("https://www.baidu.com/", null, null);
        //String s2 = HttpsClientUtil.sendHttsPostJson("https://www.baidu.com/", null, null);
        System.out.println(s);
    }
}
